<?php

namespace app\traits;

use think\facade\Cache as Facade;
use think\helper\Str;

trait Cache
{
    protected static function getCacheKey($type = 'Kvs'){
        return substr(__CLASS__, strrpos(__CLASS__, '\\') + 1) . $type;
    }
    public static function list($index = 'id'){
        $key = self::getCacheKey('List');
        $list = cache($key);
        if($list === false || $list === null){
            $list = self::where([])->column('*', $index);
            cache($key, $list);
        }
        return $list;
    }
    public static function val($id, string $field = 'name', string $index = 'id'){
        $key = self::getCacheKey('Kvs' . Str::camel($field));
        if(redis()->hexists($key, $id)){
            $val = redis()->hget($key, $id);
            return $val;
        }
        $val = self::where($index, '=', $id)->field($field)->value($field);
        redis()->hset($key, $id, $val);
        return $val; 
    }
    public static function kvs($ids = [], string $field = 'name', string $index = 'id'){
        $key = self::getCacheKey('Kvs' . Str::camel($field));
        $vals = [];
        if(Facade::has($key)){
            $vals = empty($ids) ?  redis()->hgetall($key) : redis()->hmget($key, $ids);
            return $vals;
        }
        if(empty($ids)){
            $rows = self::field([$index, $field])->select()->toArray();
        } else {
            $rows = self::whereIn($index, $ids)->field([$index, $field])->select()->toArray();
        }
        $vals = array_column($rows, $field, $index);
        redis()->hmset($key, $vals);
        return $vals;
    }
}
